package org.zero.onlinesubject.controller;

import cn.hutool.core.codec.Base64Encoder;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.zero.onlinesubject.common.constant.RedisConstant;
import org.zero.onlinesubject.common.param.LoginParam;
import org.zero.onlinesubject.common.param.RegisterParam;
import org.zero.onlinesubject.common.vo.PageResult;
import org.zero.onlinesubject.common.vo.Result;
import org.zero.onlinesubject.common.vo.UserVo;
import org.zero.onlinesubject.entity.Role;
import org.zero.onlinesubject.entity.User;
import org.zero.onlinesubject.service.UserService;
import org.zero.onlinesubject.utils.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user/api")
@CrossOrigin(origins = "*")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/getBizId")
    public Result<String> createBizId(){
        return Result.ok(IDWorker.createUID());
    }

    // 创建验证码
    @GetMapping("/captcha")
    public Result<String> createCaptcha(){
        byte[] buff = MyCaptchaUtil.generateCaptcha();
        String data = "data:image/png;base64," + Base64Encoder.encode(buff);
        return Result.ok("获取验证码成功",data);
    }

    // 退出登录
    @GetMapping("/logout")
    public Result<String> doLogout(){
        String id = UserContextHolder.get().getUserid();
        Boolean flag = stringRedisTemplate.delete(RedisConstant.TOKEN_PREFIX+id);
        return Result.ok("退出登录成功");
    }

    // 登录
    @PostMapping("/login")
    public Result<String> doLogin(@RequestBody LoginParam param){
        if (!ValidatorUtil.isName(param.getUsername()) && !ValidatorUtil.isPhone(param.getUsername())) {
            return Result.error(401,"认证失败,请检查用户名密码");
        }
        if (!MyCaptchaUtil.checkCode(param.getCaptcha())) {
            System.out.println("code: "+param.getCaptcha());
            System.out.println(JSON.toJSONString(MyCaptchaUtil.codeMap));
            return Result.error(401,"验证码错误，请重新获取验证码");
        }
        return userService.doLogin(param,false);
    }

    // 注册
    @PostMapping("/register")
    public Result<String> doRegister(@RequestBody RegisterParam param){
        Result<User> result = userService.doRegister(param);
        if(result.getData()==null){
            return Result.error(result.getCode(),result.getMsg());
        }
        LoginParam loginParam = new LoginParam();
        loginParam.setUsername(param.getUsername());
        loginParam.setPassword(param.getPassword());

        return userService.doLogin(loginParam, true);
    }

    // 获取角色列表
    @GetMapping("/roleList")
    public Result<List<Role>> getRoleList(){
        List<Role> roleList = userService.getRoleList();
        return Result.ok(roleList);
    }

    // 获取用户详情信息
    @GetMapping("/userInfo")
    public Result<UserVo> getUserInfo(String userId){
        UserVo userVo = null;
        if(StringUtils.isNullOrEmpty(userId)){
            userVo = userService.getUserVo(UserContextHolder.get().getUserid());
        }else{
            userVo = userService.getUserVo(userId);
        }

        if(userVo==null){
            return Result.error(500,"用户信息不存在");
        }
        return Result.ok(userVo);
    }

    // 更新用户信息
    @PostMapping("/update")
    public Result<String> updateUserInfo(@RequestBody User user){
        if (!ValidatorUtil.isName(user.getUsername())) {
            return Result.error(500,"用户名格式错误，请检查后重试");
        }
        if(!StringUtils.isNullOrEmpty(user.getEmail())){
            if(!ValidatorUtil.isEmail(user.getEmail())){
                return Result.error(500,"邮箱格式错误，请检查后重试");
            }
        }
        if(!StringUtils.isNullOrEmpty(user.getPhone())){
            if(!ValidatorUtil.isPhone(user.getPhone())){
                return Result.error(500,"手机号格式错误，请检查后重试");
            }
        }
        boolean flag = userService.updateById(user);
        stringRedisTemplate.delete(RedisConstant.USER_INFO_PREFIX+user.getUserid());
        if(!flag){
            return Result.error(500,"更新用户信息失败");
        }
        return Result.ok("更新用户信息成功");
    }

    // 批量获取用户列表
    @GetMapping("/userList")
    public PageResult<UserVo> getUserList(String classId, Integer roleId, Integer current, Integer size){
        if(size == null){
            size = 10;
        }
        if(current==null){
            current = 1;
        }else{
            current = (current - 1) * size;
        }
        List<UserVo> voList = userService.getUserList(classId, roleId, current, size);
        int total = userService.getUserCount(classId,roleId);

        return new PageResult<>(voList,current,total);
    }

    // 密码修改
    @PostMapping("/pwdChange")
    public Result<String> pwdChange(String newPass){
        if (StringUtils.isNullOrEmpty(newPass)) {
            return Result.error(500,"新密码不能为空");
        }
        Boolean flag = userService.pwdChange(newPass);
        return flag ? Result.ok("密码修改成功,请重新登录"):Result.error(500,"密码修改失败请重试");
    }

    // 验证码发送
    @GetMapping("/sendCaptcha")
    public Result<String> sendCaptcha(String email){
        if (!ValidatorUtil.isEmail(email)) {
           return Result.error(500,"邮箱格式错误，请检查后重试");
        }
        Boolean flag = userService.sendCaptcha(email);
        return flag ? Result.ok("验证码发送成功，请查收邮箱"):Result.error(500,"验证码发送失败，请重试");
    }

    // 校验邮箱验证码
    @GetMapping("checkCode")
    public Result<String> checkCode(String email,String code){
        if(StringUtils.isNullOrEmpty(email)){
            return Result.error(500,"邮箱不能为空");
        }
        if(StringUtils.isNullOrEmpty(code)){
            return Result.error(500,"验证码不能为空");
        }
        return userService.checkCode(email,code);
    }

    // 校验登录验证码
    @GetMapping("/verifyCaptcha")
    public Result<String> verifyCaptcha(String code){
        if(StringUtils.isNullOrEmpty(code)){
            return Result.error(500,"验证码不能为空");
        }
        Boolean flag = userService.verifyCaptcha(code);
        return flag ? Result.ok("验证码校验成功"):Result.error(500,"验证码校验失败");
    }
}
